package com.ktgj.customer.controller;

import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.CardDTO;
import com.ktgj.customer.domain.dto.RightdetailDTO;
import com.ktgj.customer.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购卡Controller
 *
 * @author ruoyi
 * @date 2021-07-30
 */
@ControllerAdvice
@RestController
@RequestMapping("/cardAPPPurchase")
public class CardAPPPurchaseController extends BaseController {
    @Autowired
    private ICardPurchaseService cardPurchaseService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICardService cardService;
    @Autowired
    private IPointRecordService recordService;
    @Autowired
    private IDepositBusinessService depositBusinessService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICustomerService customerService;

    /**
     * app 购买卡预下单页面信息展示查询
     *
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("queryCardOrderInfo")
    public AjaxResult queryCardOrderInfo(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long cardId = Long.valueOf(map.get("cardId").toString());
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//用户信息
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("customerAvatar", customer.getAvatar());
        result.put("customerNickName", customer.getNickName());
        result.put("customerName", customer.getCustomerName());
        result.put("customerPhone", customer.getContractPhoneOne());
        result.put("customerIdType", customer.getIdType());
        result.put("customerCertificateNo", customer.getCustCertificateNo());
        Long aLong;
        try {
            aLong = recordService.queryUserCreditsNum(customer.getCustomerId());
        } catch (Exception e) {
            aLong = 0L;
        }
        result.put("points", aLong);
        BigDecimal bLong = depositBusinessService.queyUserDepositBusiness(customer.getCustomerId());
        result.put("depositBusiness", bLong);

        CardDTO card = cardService.selectCardAndRightDetailById(cardId);//卡信息
        CouponDto couponDto = couponService.queyUserCoupon(customer.getCustomerId(), card.getPrice());
        result.put("coupon", couponDto);


        result.put("cardId", card.getCardId());
        result.put("cardName", card.getCardSectionName());
        result.put("cardPrice", card.getPrice());
        result.put("continuousPrice", card.getContinuousPrice());
        result.put("borderAndFontColor", card.getCardNameTypefaceColour());
        result.put("backgroundImageUrl", card.getBackgroundImageurl());
        List<Map<String, String>> list = new ArrayList<>();

        for (RightdetailDTO item : card.getRightdetailDTOS()) {
            Map<String, String> rightDetail = new HashMap<>();
            rightDetail.put("logoUrl", item.getLogoUrl());
            rightDetail.put("rightDetailName", item.getRightdetailName());
            switch (item.getCouponType()) {
                case "CouponTypeFullMinus":
                case "CouponTypeCashCoupon":
                case "CouponTypeDiscount":
                case "CouponTypeAdmissionTicket":
                    rightDetail.put("rightDetailIntroduce",item.getNumberOfTimes() + "张");
                    break;
                case "CouponTypeRegister":
                case "CouponTypeTest":
                case "CouponTypeFlightDelay":
                case "CouponTypeFlightDCancellation":
                    rightDetail.put("rightDetailIntroduce",item.getNumberOfTimes() + "次");
                    break;
                case "CouponTypeInfiniteRegister":
                case "CouponTypeInfiniteConsultation":
                case "CouponTypeDoctor":
                    rightDetail.put("rightDetailIntroduce","无限次");
                    break;
                case "CouponTypeCommodity":
                case "CouponTypeTravel":
                    rightDetail.put("rightDetailIntroduce",item.getCouponMoney() + "元");
                    break;
                case "CouponTypeVIPHall":
                    rightDetail.put("rightDetailIntroduce","本人" + item.getNumberOfTimes() + "次");
                    break;
                case "CouponTypeInfiniteVIPHall":
                    rightDetail.put("rightDetailIntroduce","本人无限次");
                    break;
                case "CouponTypeDD":
                    rightDetail.put("rightDetailIntroduce",item.getNumberOfTimes() + "张");
                    break;
                case "CouponTypeCommodityReceive":
                    rightDetail.put("rightDetailIntroduce",item.getCouponMoney() + "元");
                    break;
            }
            list.add(rightDetail);
        }
        result.put("rightDetail", list);
        return AjaxResult.success(result);
    }

    /**
     * app 购卡下单接口（点击支付按钮进入支付操作前）
     *
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("buyCardOrder")
    public AjaxResult buyCardOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) throws Exception {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

        Customer upd = new Customer();
        upd.setCustomerId(customer.getCustomerId());
        upd.setCustomerName(map.get("customerName").toString());
        upd.setIdType(map.get("customerIdType").toString());
        upd.setCustCertificateNo(map.get("customerCertificateNo").toString());
        String phone = map.get("customerPhone").toString();
        if (!phone.equals(customer.getContractPhoneOne()) && !phone.equals(customer.getContractPhoneTow())) {
            upd.setContractPhoneTow(phone);
        }
        upd = customerService.updateCustomer(upd, request.getHeader("token"));

        boolean usePoint = getUsePoint(map);//是否使用积分
        boolean useDeposit = getUseDeposit(map);//是否使用金币（预留款）
        Long couponId = getCouponId(map);//优惠卷id

        String years = map.get("years").toString();//购买年限

        Long cardId = Long.valueOf(map.get("cardId").toString());//卡id

        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额

        List<Integer> product = new ArrayList<>();
        if (map.get("products") != null) {
            Object products = map.get("products");
            product = objToList(products, Integer.class);
        }

        if (map.get("otherPhone") != null && !map.get("otherPhone").toString().equals("")) {
            Customer otherUpd = new Customer();
            otherUpd.setCustomerName(map.get("otherCustomerName").toString());
            otherUpd.setIdType(map.get("otherIdType").toString());
            otherUpd.setCustCertificateNo(map.get("otherCustCertificateNo").toString());
            String otherPhone = map.get("otherPhone").toString();

            Customer otherCustomer = customerService.customerPhoneLogin(otherPhone);
            if (otherCustomer == null) {//如果没有此用户，为用户注册
                otherUpd.setContractPhoneOne(otherPhone);
                otherCustomer = loginService.register(otherUpd, null);
                otherUpd.setCustomerId(otherCustomer.getCustomerId());
            } else {//如果有该用户，为该用户修改
                otherUpd.setCustomerId(otherCustomer.getCustomerId());
                Customer re = customerService.selectCustomerPhoneById(otherUpd.getCustomerId());
                if (!otherPhone.equals(re.getContractPhoneOne()) && !otherPhone.equals(re.getContractPhoneTow())) {
                    otherUpd.setContractPhoneTow(otherPhone);
                }
                customerService.update(otherUpd);//以上为修改购买用户的用户信息
            }

            String s;
            try {
                s = cardPurchaseService.appPuyCardOrder(upd.getCustomerId(), cardId, usePoint, couponId, usedMoney, useDeposit, years, otherUpd.getCustomerId(), product);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            Map<String, Object> map1 = new HashMap<>();
            map1.put("OrderNum", s);
            map1.put("customer", otherUpd);
            return AjaxResult.success(map1);
        }

        String s;
        try {
            s = cardPurchaseService.appPuyCardOrder(customer.getCustomerId(), cardId, usePoint, couponId, usedMoney, useDeposit, years, customer.getCustomerId(), product);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("OrderNum", s);
        map1.put("customer", upd);
        return AjaxResult.success(map1);
    }

    public static <T> List<T> objToList(Object obj, Class<T> cla) {
        List<T> list = new ArrayList<T>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                list.add(cla.cast(o));
            }
            return list;
        }
        return null;
    }

    /**
     * 预支付页面信息展示查询
     *
     * @param map
     * @return
     */
    @PostMapping("queryOrderInfoByNum")
    public AjaxResult queryOrderInfoByNum(@RequestBody Map<String, Object> map) {
        String orderNum = map.get("orderNum").toString();
        return AjaxResult.success(cardPurchaseService.queryOrderInfoByNum(orderNum));
    }

    /**
     * 微信小程序支付
     * @param map
     * @return
     */
    @PostMapping("/wechatPay")
    public AjaxResult wechatPay(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String openId = map.get("openId");
        String orderNumber = map.get("orderNumber");

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount"));
        }

        String type = map.get("type");

        Map<String, Object> wechat;
        try {
            wechat = cardPurchaseService.wechatPay(openId, orderNumber, request, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (wechat != null)
            return AjaxResult.success(wechat);
        else
            return AjaxResult.error("支付失败");
    }

    /**
     * 支付成功后，支付回调接口
     *
     * @param request
     * @param map
     */
    @PostMapping("getOrderResult")
    public void getOrderResult(HttpServletRequest request, @RequestBody Map<String, Object> map) throws ParseException {
        /**
         * 此处略过回调判断支付成功失败的流程
         */
        boolean bool = true;//回调返回值
        String orderNum = map.get("orderNum").toString();
        String partyPayNum = map.get("partyPayNum").toString();
        cardPurchaseService.orderResult(bool, orderNum, partyPayNum);
    }

    /**
     * 查询待支付订单
     *
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("getWaitPayOrder")
    public AjaxResult getWaitPayOrder(HttpServletRequest request) {
        Customer customer;
        try {
            customer = loginService.getLoginCustomer(request);//会员id
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(cardPurchaseService.getWaitPayOrder(customer.getCustomerId()));
    }

    public Long getCouponId(Map<String, Object> map) {
        if (map.get("couponId") != null)
            return Long.valueOf(map.get("couponId").toString());//优惠卷id
        return null;
    }

//    public BigDecimal getCouponMoney(Map<String, Object> map) {
//        if (map.get("couponMoney") != null)
//            return new BigDecimal(map.get("couponMoney").toString());//优惠卷优惠金额
//        return null;
//    }

    public boolean getUsePoint(Map<String, Object> map) {
        if (map.get("usePoint") != null)
            return (Boolean)map.get("usePoint");//是否使用积分
        return false;
    }

    public boolean getUseDeposit(Map<String, Object> map) {
        if (map.get("useDeposit") != null)
            return (Boolean)map.get("useDeposit");//是否使用金币（预留款）
        return false;
    }


    //    /**
//     * app 购买权益包预下单页面信息展示查询
//     *
//     * @param request
//     * @param map
//     * @return
//     */
//    @SignatureValidation
//    @PostMapping("queryPackOrderInfo")
//    public AjaxResult queryPackOrderInfo(HttpServletRequest request, @RequestBody Map<String, Object> map) {
//        Long packId = Long.valueOf(map.get("packId").toString());
//        Customer customer;
//        try {
//            customer = loginService.getLoginCustomer(request);//用户信息
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//        EquityPack equityPack = equityPackService.selectEquityPackById(packId);//权益包信息
//        Map<String, Object> result = new HashMap<>();
//        result.put("customer", customer);
//        result.put("packId", equityPack.getEquitypackId());
//        result.put("packName", equityPack.getEquitypackName());
//        result.put("packPrice", equityPack.getPrice());
//        Long aLong;
//        try {
//            aLong = recordService.queryUserCreditsNum(customer.getCustomerId());
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//
//        result.put("creditsNum", aLong);
//
//        return AjaxResult.success(result);
//    }

    //    /**
//     * app 购权益包下单接口（点击支付按钮进入支付操作前）
//     *
//     * @param request
//     * @param map
//     * @return
//     */
//    @SignatureValidation
//    @PostMapping("buyPackOrder")
//    public AjaxResult buyPackOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
//        Customer customer;
//        try {
//            customer = loginService.getLoginCustomer(request);//会员id
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//        Long packId = Long.valueOf(map.get("packId").toString());//权益包id
//        Long creditsNum = getCreditsNum(map);//积分数量
//        Long couponId = getCouponId(map);//优惠卷id
//        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
//        BigDecimal couponMoney = getCouponMoney(map);//优惠卷优惠金额
//        BigDecimal usedDeposit = getUsedDeposit(map);//预留款
//        return AjaxResult.success(cardPurchaseService.buyCardOrder(customer.getCustomerId(), packId, creditsNum, couponId, usedMoney, couponMoney, usedDeposit, CustomerConstants.newPack.getValue()));
//    }

//    /**
//     * app 购卡续费下单接口（点击支付按钮进入支付操作前）
//     *
//     * @param request
//     * @param map
//     * @return
//     */
//    @SignatureValidation
//    @PostMapping("buyRenewCardOrder")
//    public AjaxResult buyRenewCardOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
//        Customer customer;
//        try {
//            customer = loginService.getLoginCustomer(request);//会员id
//        } catch (Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
//        Long customerCardId = Long.valueOf(map.get("customerCardId").toString());//卡id
//        Long creditsNum = getCreditsNum(map);//积分数量
//        Long couponId = getCouponId(map);//优惠卷id
//        BigDecimal usedMoney = new BigDecimal(map.get("usedMoney").toString());//实付金额
//        BigDecimal couponMoney = getCouponMoney(map);//优惠卷优惠金额
//        BigDecimal usedDeposit = getUsedDeposit(map);//预留款
//        return AjaxResult.success(cardPurchaseService.buyCardOrder(customer.getCustomerId(), customerCardId, creditsNum, couponId, usedMoney, couponMoney, usedDeposit, CustomerConstants.renewCard.getValue()));
//    }
}
